package bavaria.hightech.banking.account;

import java.util.Calendar;

import bavaria.hightech.banking.Zeit.InternalClock;
import bavaria.hightech.banking.bank.Money;
import bavaria.hightech.banking.condition.Condition;
import bavaria.hightech.banking.condition.ContractPeriod;
import bavaria.hightech.banking.condition.FixedDepositCondition;

public class FixedDepositAccount extends Account {

	private final FixedDepositCondition fixedDepositCondition;

	public FixedDepositAccount(int accountNumber, String accountHolder,
			FixedDepositCondition fixedDepositCondition) {
		super(accountNumber, accountHolder);
		this.fixedDepositCondition = fixedDepositCondition;
	}

	public void drawout(Money amount, String reason) throws Exception {
		if (amount.greaterThan(getBalance())) {
			throw new Exception(
					"You can not draw out more money than you have available. QwQ");
		}
		book(false, amount, reason);
	}

	public void calculateInterest() {
		Calendar now = InternalClock.getInstance().getCalendar();
		int durationInMonth = getDurationInMonth(now);
		ContractPeriod period = fixedDepositCondition.getContractPeriod();
		if (durationInMonth == period.getMonths()) {
			Money balance = getBalance();
			balance = balance.calculateInterest(fixedDepositCondition
					.getInterestRate() / 100);
			book(true, balance, "Ertrag durch Zinsen");
			setCreationDate(now);
		}
	}

	private int getDurationInMonth(Calendar now) {
		int creationMonth = getCreationDate().get(Calendar.MONTH);
		int creationYear = getCreationDate().get(Calendar.YEAR);
		int nowMonth = now.get(Calendar.MONTH);
		int nowYear = now.get(Calendar.YEAR);
		int durationInMonth = 0;
		if (nowMonth < creationMonth) {
			durationInMonth += nowMonth + 12 - creationMonth;
			nowYear--;
		} else {
			durationInMonth += nowMonth - creationMonth;
		}
		if (creationYear != nowYear) {
			durationInMonth += nowYear - creationYear * 12;
		}
		return durationInMonth;
	}

	@Override
	public String toString() {
		String string = "Account number: " + getNumber() + " account holder: "
				+ getAccountHolder() + " balance: " + getBalance()
				+ " interest rate: " + fixedDepositCondition.getInterestRate();
		return string;
	}

	@Override
	public Condition getCondition() {
		return fixedDepositCondition;
	}

}
